package com.nlscan.ncomgateway.core.manager

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2025/2/10
 *  desc  :
 * </pre>
 */
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.nlscan.ncomgateway.core.data.backup.PreferenceReflector
import java.io.File

object BackupManager {
    private const val BACKUP_FILE_NAME = "app_settings_backup.json"
    private val gson = Gson()

    /**
     * 备份当前配置到文件
     * @return 备份文件路径，失败返回 null
     */
    fun backup(context: Context): String? {
        return try {
            val configData = PreferenceReflector.backupAllSettings()
            val json = gson.toJson(configData)

            val backupFile = File(context.filesDir, BACKUP_FILE_NAME)
            backupFile.writeText(json)
            backupFile.absolutePath
        } catch (e: Exception) {
            Log.e("BackupManager", "Backup failed", e)
            null
        }
    }

    /**
     * 从备份文件恢复配置
     * @return 是否恢复成功
     */
    fun restore(context: Context): Boolean {
        return try {
            val backupFile = File(context.filesDir, BACKUP_FILE_NAME)
            if (!backupFile.exists()) return false

            val json = backupFile.readText()
            //val configMap = gson.fromJson<Map<String, Any>>(json, object : TypeToken<Map<String, Any>>() {})
            val configMap = gson.fromJson<Map<String, Any>>(
                json,
                object : TypeToken<Map<String, Any>>() {}.type
            )

            PreferenceReflector.restoreAllSettings(configMap)
            true
        } catch (e: Exception) {
            Log.e("BackupManager", "Restore failed", e)
            false
        }
    }
}
